import tkinter
from interface.widget import ContainerAdapter, scale, scale_factor
from tkinter import ttk, filedialog
from utils.network import recv_file
import pathlib
from PIL import Image, ImageTk


class Message(ContainerAdapter):
    x = 0
    relwidth = 1

    def __init__(self, master, message):
        ContainerAdapter.__init__(self, master)
        self.message = message

    def content(self, master):
        info_label = ttk.Label(master,
                               text='{year}-{month}-{day} {hour}:{minute}:{second}   {sender} -> {recipient}'.format(
                                   sender=self.message['sender'], recipient=self.message['recipient'],
                                   **self.message['time']
                               ))
        info_label.place(**scale(x=0, y=0, relwidth=1, height=25))

        self.tkw.update()

        text_label = ttk.Label(master, text=self.message['text'], wraplength=self.tkw.winfo_width())
        text_label.place(**scale(x=0, y=25, relwidth=1))

        def on_resize(event):
            text_label['wraplength'] = self.tkw.winfo_width()

        text_label.bind('<Configure>', on_resize)

        self.tkw.update()

        self.adjust_height()

    def adjust_height(self):
        self.tkw.place(**scale(height=self.max_children_y()))
        self.tkw.update()
        return self.tkw.winfo_height()


class FileMessage(Message):
    def __init__(self, master, message, file_info):
        Message.__init__(self, master, message)
        self.file_info = file_info

    def content(self, master):
        info_label = ttk.Label(master,
                               text='{year}-{month}-{day} {hour}:{minute}:{second}   {sender} -> {recipient}'.format(
                                   sender=self.message['sender'], recipient=self.message['recipient'],
                                   **self.message['time']
                               ))
        info_label.place(**scale(x=0, y=0, relwidth=1, height=25))

        self.tkw.update()

        ttk.Style().configure('FileMessage.FileContainer.TFrame', background='#bbbbbb')
        file_container = ttk.Frame(master, style='FileMessage.FileContainer.TFrame')
        file_container.place(**scale(x=0, y=25, relwidth=1, height=110))

        ttk.Style().configure('FileMessage.FileContainer.TLabel', background='#bbbbbb')
        file_name_label = ttk.Label(file_container, text=self.file_info['file_name'],
                                    style='FileMessage.FileContainer.TLabel')
        file_name_label.place(**scale(x=20, y=10, height=30))

        progress_bar = ttk.Progressbar(file_container, maximum=100, value=0)
        progress_bar.place(**scale(x=20, y=50, relwidth=1, width=-140, height=10))

        def download_button_method():
            dir_path = pathlib.Path(filedialog.askdirectory())
            file_path = dir_path.joinpath(self.file_info['file_name'])

            def hook(rate):
                progress_bar['value'] = rate * 100
                progress_bar.update()

            recv_file(file_path, self.file_info['file_id'], self.file_info['total_bytes'], hook)

        download_button = ttk.Button(file_container, text='下载', command=download_button_method)
        download_button.place(**scale(relx=1, x=-100, y=70, width=80, height=30))

        self.tkw.update()

        self.adjust_height()


class ImageMessage(FileMessage):

    def __init__(self, master, message, file_info):
        FileMessage.__init__(self, master, message, file_info)
        self.photo = None

    def content(self, master):
        info_label = ttk.Label(master,
                               text='{year}-{month}-{day} {hour}:{minute}:{second}   {sender} -> {recipient}'.format(
                                   sender=self.message['sender'], recipient=self.message['recipient'],
                                   **self.message['time']
                               ))
        info_label.place(**scale(x=0, y=0, relwidth=1, height=25))

        self.tkw.update()

        file_path = './.cache/{}/{}'.format(self.file_info['file_id'], self.file_info['file_name'])
        recv_file(file_path, self.file_info['file_id'])

        image = Image.open(file_path)
        w, h = image.size
        f = w / 400 / scale_factor
        image = image.resize((int(w / f), int(h / f)))
        self.photo = ImageTk.PhotoImage(image)
        image_label = tkinter.Label(master, image=self.photo)
        image_label.place(**scale(x=0, y=25))

        self.tkw.update()

        self.adjust_height()
